package com.fenxiangtech.mall.controller;

import com.alibaba.fastjson.JSON;
import com.fenxiangtech.mall.base.BaseResponse;
import com.fenxiangtech.mall.base.PageData;
import com.fenxiangtech.mall.manager.OrderManager;
import com.fenxiangtech.mall.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lixiang
 * @CreateTime 2018/10/27
 **/
@Controller
public class OrderController extends AbstractBaseController {
    @Autowired
    private OrderManager orderManager;

    @GetMapping("/order/query")
    @ResponseBody
    public BaseResponse<PageData<Order>> queryOrder(Order order, Integer pageIndex , Integer pageSize){

        List<Order> orders = orderManager.queryOrder(order, pageIndex, pageSize);
        Long totalCount = orderManager.countOrder(order);

        pageIndex = pageIndex == null?1:pageIndex;
        pageSize = pageSize == null?20:pageSize;
        return  BaseResponse.assemblePageResponse(orders,totalCount,pageIndex,pageSize);
    }

    @PostMapping("/order/save")
    @ResponseBody
    public BaseResponse<String> saveItem(Order order){
        BaseResponse<String> baseResponse = new BaseResponse<>();
        orderManager.saveOrder(order);
        baseResponse.setData("OK");
        return  baseResponse;
    }

    @GetMapping("/order/list")
    @ResponseBody
    public String listItem(Order order, Integer pageNumber , Integer pageSize){

        Map<String,Object> map  = new HashMap<>();

        List<Order> orders = orderManager.queryOrder(order, pageNumber, pageSize);
        Long totalCount = orderManager.countOrder(order);
        map.put("total",totalCount);
        map.put("rows",orders);
        return JSON.toJSONString(map);
    }
    
    @GetMapping("/order/get")
    @ResponseBody
    public Order listItem(Order order){
    
        List<Order> orders = orderManager.queryOrder(order, 1, 1);
        if(orders!=null && orders.size()>0){
            return orders.get(0);
        }else{
            return new Order();
        }
    }

    @GetMapping("/order/delete")
    @ResponseBody
    public String delete(Long id){
        orderManager.deleteOrder(id);
        return "OK";
    }

}
